/* eslint-disable no-unused-vars */
import React, { useRef, useEffect } from 'react';
import {
    PlusOutlined,
    EyeTwoTone,
    EyeInvisibleOutlined,
    CarryOutOutlined
} from '@ant-design/icons';
import { connect } from 'react-redux'
import { YzhTable, YzhTree, YzhProgressDialog } from '@com'
import { useCustomState } from '@/hooks/useEffect';
import {
    Button,
    Input,
    Switch,
    Tag,
    Select,
    TreeSelect,
    Card, Col, Row,
    Form, message,
    Modal
} from 'antd';
import api from '@/api/apiList'
import { arrayToTree, setTreeProps, ValidationRules } from '@/utils'
import { storage } from '@/utils/storage'
import YzhPwdDialog from './resetPwd'
import {
    hasPermission,
    hasRoles,
    permissionCodes as pCodes
} from '@/routes/permission'
import {
    ADD_TABS,
    REMOVE_TABS,
    CHANGE_TABS,
    FILTER_TABS,
} from '@/store/actionTypes'
const { confirm } = Modal;
const { Option } = Select;
const UserManage = (props) => {
    const actionRef = useRef();
    const formRef = useRef();
    const [form] = Form.useForm();
    const progressDialogRef = useRef(null);
    let userInfo = storage.get('userInfo')
    userInfo = userInfo && userInfo !== null ? userInfo : {}

    const [loading, setLoading] = useCustomState(false)
    let clientHeight = document.body.clientHeight
    const [state, setState] = useCustomState({
        deptId: undefined,
        levelOptions: [{
            value: '',
            label: '全部',
        }, {
            value: 1001,
            label: '普通员工',
        }, {
            value: 1002,
            label: '上级',
        }],
        statusOptions: [{
            label: '全部',
            value: '',
        }, {
            label: '启用',
            value: 1001,
        }, {
            label: '禁用',
            value: 1002,
        }],
        roleVisiable: false,
        passwordVisiable: false,
        loaded: false,
        userId: '',
        roleIds: [],
        roleList: [],
        treeData: [],
        sourceTreeData: []
    });
    const [scroll, setScroll] = useCustomState(props.scroll || { x: 1500, y: clientHeight });
    useEffect(() => {
        const initData = async () => {
            try {
                setLoading(true)
                let tree = await api.userCenter.department.tree({}, pCodes.user.list)
                api.userCenter.role.listAll().then(role => {
                    let roleList = role && role.result !== null ? role.result : []
                    roleList = roleList.map(el => {
                        return {
                            // ...el,
                            label: el.name,
                            value: el.id
                        }
                    })
                    setState({
                        ...state,
                        roleList,
                        loaded: true
                    })
                    // setLoading(false)
                })
                let treeData = tree && tree.result !== null ? tree.result : []
                treeData = arrayToTree(treeData, { children: 'nodes', pId: 'pid', id: 'id' })
                let newExpandedKeys = setTreeProps(treeData).newExpandedKeys
                treeData = setTreeProps(treeData, () => ({ icon: <CarryOutOutlined /> })).tree
                setState({
                    deptId: undefined,
                    ...state,
                    treeData,
                    sourceTreeData: treeData,
                    loaded: true,
                    defaultExpandedKeys: newExpandedKeys
                })
                setLoading(false)
            } catch (error) {
                console.log(error);
            }
        }
        setScroll(props.scroll)
        !state.loaded && initData()
    }, [props, state])
    const columns = [
        {
            title: '关键词',
            dataIndex: 'kwd',
            align: 'center',
            order: 3,
            // sorter: true,
            hideInTable: true,
            width: 220,
            // tip: '名称/编码',
            renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
                if (type === 'form') {
                    return null;
                }
                return (
                    // value 和 onchange 会通过 form 自动注入。
                    <Input
                        // 组件的配置
                        {...fieldProps}
                        allowClear
                        // 自定义配置
                        key="account"
                        placeholder="请输入账号/姓名/手机号"
                    />
                );
            },
        },
        {
            title: '账号',
            dataIndex: 'account',
            hideInSearch: true,
            align: 'center',
            ellipsis: true,
            // sorter: true,
            width: 160
        },
        {
            title: '姓名',
            dataIndex: 'name',
            hideInSearch: true,
            align: 'center',
            ellipsis: true,
            // sorter: true,
            width: 160
        },
        {
            title: '部门',
            dataIndex: 'deptName',
            hideInSearch: true,
            ellipsis: true,
            width: 220
        },
        {
            title: '角色',
            dataIndex: 'roleId',
            hideInTable: true,
            // ellipsis: true,
            order: 2,
            valueType: 'select',
            fieldProps: {
                allowClear: true,
                // mode: 'tags',
                // maxTagCount: 1,
                // maxTagTextLength: 6,
                showSearch: true,
                defaultValue: '',
                options: [{ label: '全部', value: '' }, ...state.roleList],
                placeholder: '请选择或输入角色名称'
            },
        },
        {
            title: '角色',
            dataIndex: 'roleIdsName',
            hideInSearch: true,
            ellipsis: true,
            width: 220
        },
        {
            title: '等级',
            dataIndex: 'userLevel',
            // hideInSearch: true,
            align: 'center',
            width: 120,
            renderFormItem: (_, { type, fieldProps }, form) => {
                if (type === 'form') {
                    return null;
                }
                return (
                    // value 和 onchange 会通过 form 自动注入。
                    <Select
                        showSearch
                        allowClear
                        placeholder="请选择等级"
                        optionFilterProp="label"
                        // 组件的配置
                        {...fieldProps}
                        // 自定义配置
                        key="userLevel"
                        defaultValue=''
                        filterOption={(input, option) => {
                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        }>
                        {
                            state.levelOptions.map(el => {
                                return <Option key={el.value} value={el.value} label={el.label}>{el.label}</Option>
                            })
                        }
                    </Select>
                );
            },
            render: (t, r) => {
                return r.userLevel && r.userLevel.description
            },
        },
        // {
        //     title: '邮箱',
        //     dataIndex: 'email',
        //     hideInSearch: true,
        //     width: 220
        // },
        {
            title: '电话',
            dataIndex: 'phone',
            hideInSearch: true,
            align: 'center',
            width: 220
        },
        {
            title: '创建时间',
            key: 'showTime',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            align: 'center',
            // sorter: true,
            width: 220,
            hideInSearch: true,
        },
        // {
        //     title: '创建时间',
        //     dataIndex: 'createTime',
        //     valueType: 'dateTimeRange',
        //     width: 220,
        //     // hideInSearch: true,
        //     hideInTable: true,
        //     search: {
        //         transform: (value) => {
        //             return {
        //                 startTime: value[0],
        //                 endTime: value[1],
        //             };
        //         },
        //     },
        // },
        {
            title: '状态',
            dataIndex: 'userStatus',
            // valueType: 'select',
            align: 'center',
            order: 1,
            width: 120,
            renderFormItem: (_, { type, fieldProps }, form) => {
                if (type === 'form') {
                    return null;
                }
                return (
                    // value 和 onchange 会通过 form 自动注入。
                    <Select
                        showSearch
                        allowClear
                        placeholder="请选择状态"
                        optionFilterProp="label"
                        // 组件的配置
                        {...fieldProps}
                        // 自定义配置
                        key="userLevel"
                        defaultValue=''
                        filterOption={(input, option) => {
                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        }>
                        {
                            state.statusOptions.map(el => {
                                return <Option key={el.value} value={el.value} label={el.label}>{el.label}</Option>
                            })
                        }
                    </Select>
                );
            },
            render: (text, record, _, action) =>
                record.userStatus && <Switch
                    checkedChildren="启用"
                    unCheckedChildren="禁用"
                    disabled={!hasPermission([pCodes.user.status])}
                    onChange={(value) => changeStatus(record.id, value)}
                    defaultChecked={record.userStatus.code === 1001} />,
        },
        {
            title: '操作',
            valueType: 'option',
            align: 'center',
            fixed: 'right',
            hideInSearch: true,
            width: 260,
            render: (text, record, _, action) => [
                (hasPermission([pCodes.user.edit]) && <a type="link" key="editable" onClick={() => {
                    props.addTabs({ activeKey: '/userCenter/edit', title: '编辑用户', query: { id: record.id } })
                    // props.history.push('/userCenter/edit?id=' + record.id)
                }}>
                    编辑
                </a>),
                (hasPermission([pCodes.user.del]) && userInfo.userId !== record.id && record.id !== 1 && <a type="link"
                    onClick={() => {
                        confirm({
                            title: '温馨提示',
                            centered: true,
                            content: <div style={{ fontSize: 14 }} >删除后数据无法复原，且用户无法登录后台是否确认删除该用户？</div>,
                            onOk: () => onDelete(record, action),
                            onCancel () { },
                        });
                    }} key="delete">
                    删除
                </a>),
                (hasPermission([pCodes.user.Assign_roles]) && record.id != 1 && <a type="link" onClick={() => {
                    setState({
                        ...state,
                        roleVisiable: true,
                        userId: record.id,
                        roleIds: record.roleIds || []
                    })
                }} key="roles">
                    分配角色
                </a>),
                (hasPermission([pCodes.user.reset_password]) && <a type="link" onClick={() => setState({
                    ...state,
                    userId: record.id,
                    passwordVisiable: true,
                })} key="reset">
                    重置密码
                </a>),
            ],
        },
    ];

    const onExport = () => {
        progressDialogRef.current.start()
    }

    const changeStatus = async (id, value) => {
        // progressDialogRef.current.start()
        // unfreeze
        // freeze
        console.log(value, 'value');
        let apiStr = value ? 'unfreeze' : 'freeze'
        let res = await api.userCenter.user[apiStr]({ id })
        res && res.success && message.success(res.message)
        actionRef.current.reload()
    }
    const getTableData = async (params, sort, filter) => {
        const { current, ...others } = params
        let res = await api.userCenter.user.list({ ...others, currentPage: current })
        if (!res || res.result === null) {
            return { data: [], total: 0, success: true }
        }
        return { data: res.result.records, total: res.result.page.totalRow, success: true };
    }
    const onTreeSelect = (keys, parentNode, current) => {
        let deptId = keys && keys instanceof Array ? keys[0] : keys
        let parent = parentNode && [parentNode] || state.sourceTreeData
        setLoading(true)
        setState({ ...state, refresh: !keys, deptId })
        setTimeout(() => {
            let newExpandedKeys = setTreeProps(parent).newExpandedKeys
            if (current) {
                setState({ ...state, refresh: false, deptId })
            } else {
                setState({ ...state, refresh: false, deptId, treeData: parent, defaultExpandedKeys: newExpandedKeys })
            }
            formRef.current.setFieldsValue({ deptId })
            setLoading(false)
        });
        // actionRef.reload()
    }
    // 删除
    const onDelete = async (record, action) => {
        let res = await api.userCenter.user.remove({ id: record.id })
        res && res.success && message.success(res.message || '操作成功')
        action.reload()
    }
    // 修改角色
    const onChangeRole = async () => {
        if (!state.roleIds.length) {
            message.error('请选择角色！')
            return
        }
        let res = await api.userCenter.user.setRole({ userId: state.userId, roleIds: state.roleIds })
        if (res && res.success) {
            message.success(res.message)
            setState({
                ...state,
                roleVisiable: false
            })
            if (storage.get('userInfo').userId &&
                storage.get('userInfo').userId === state.userId) {
                message.success(props.globalConfig.setting.message.auth)
                props.logout()
                props.filterTabs('3')
                return
            }
            actionRef.current.reload()
        }
    }
    const { roleVisiable, passwordVisiable } = state
    const { themeConfig } = props
    return (
        <Card className="user-manage" bordered={false} bodyStyle={{ padding: 0 }}>
            <Row gutter={0}>
                <Col xxl={4} xl={6} lg={24} md={24} xs={24} sm={24}>
                    <YzhTree
                        onSelect={onTreeSelect}
                        value={state.deptId}
                        refresh={state.refresh}
                        pcode={pCodes.user.list}
                        style={{
                            maxHeight: themeConfig.showFooter ? scroll.y - 260 : scroll.y - 160,
                            overflow: 'auto',
                            padding: 20,
                            borderRight: '1px dashed #ccc',
                            overflowY: 'auto'
                        }} />
                </Col>
                <Col xxl={20} xl={18} lg={24} md={24} xs={24} sm={24}>
                    {<YzhTable
                        params={{ deptId: state.deptId }}
                        columns={columns}
                        tableStyle={{ paddingTop: !hasPermission([pCodes.user.add]) && 30 }}
                        scroll={{
                            x: scroll.x,
                            y: hasPermission([pCodes.user.add]) ? scroll.y - 390 : scroll.y - 360
                        }}
                        onReset={() => {
                            onTreeSelect()
                            formRef.current.setFieldsValue({ deptId: null, userStatus: '' })
                        }}
                        actionRef={actionRef}
                        formRef={formRef}
                        request={async (params = {}, sort, filter) => getTableData(params, sort, filter)}
                        editable={{
                            type: 'multiple',
                        }}
                        rowKey="id"
                        tableExtraRender={() => hasPermission([pCodes.user.add]) && [
                            <Button key="add" onClick={() => {
                                props.addTabs({ activeKey: '/userCenter/add', title: '新增用户' }, props.history)
                                props.history.push('/userCenter/add')
                            }} style={{ marginRight: 8 }} icon={<PlusOutlined />} type="primary">
                                新增用户
                            </Button>,
                        ]}
                    />}
                </Col>
            </Row>
            {<Modal
                maskClosable={false}
                centered
                title="选择角色"
                width={500}
                wrapClassName="yzh-modal"
                visible={roleVisiable}
                onOk={onChangeRole}
                onCancel={() => {
                    setState({
                        ...state,
                        roleVisiable: false,
                    })
                }}>
                {roleVisiable ? <Select
                    showSearch
                    mode="multiple"
                    style={{ width: '100%' }}
                    placeholder="请选择角色"
                    value={state.roleIds || []}
                    optionFilterProp="label"
                    onChange={(values) => {
                        console.log(values, 'values');
                        setState({
                            ...state,
                            roleIds: values,
                            // roleVisiable: false,
                        })
                    }}
                    filterOption={(input, option) => {
                        return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    }>
                    {
                        state.roleList.map(el => {
                            return <Option key={el.value} value={el.value} label={el.label}>{el.label}</Option>
                        })
                    }
                </Select> : null}
            </Modal>}
            {<YzhPwdDialog visable={state.passwordVisiable} {...props} userId={state.userId} onClose={() => {
                setState({
                    ...state,
                    passwordVisiable: false
                })
                actionRef.current.reload()
            }} />}
            <YzhProgressDialog ref={progressDialogRef} />
        </Card>
    );
};
export default UserManage;
